#include <REGX52.H>
#include "Key.h"
#include "Delay.h"
#include "Nixie.h"
#include "Timer0.h"
#include "AT24C02.h"
#include "MatrixKey.h"

sbit BUZZER=P2^5;

unsigned char keym,k;
 char min,sec,minisec,m;
unsigned char flag;

void main()
{
    Timer0_Init();
    m=1;
    while(1)
    {      
        keym=Key();
        k=MatrixKey();
        if(k==1)
        {
            min++;
        }
        if(k==2)
        {
            min--;
        }
        if(k==3)
        {
            sec++;
        }
        if(k==4)
        {
            sec--;
        }
        if(k==5)
        {
            m=1;
        }
        if(k==6)
        {
            m=0;
        }

        if(keym==1)
        {
            flag=!flag;
        }
        if(keym==2)
        {
            min=0;
            sec=0;
            minisec=0;
        }
        if(keym==3)
        {
            AT24C02_WriteByte(0,min);
            Delay(5);
            AT24C02_WriteByte(1,sec);
            Delay(5);
            AT24C02_WriteByte(2,minisec);
            Delay(5);
        }
        if(keym==4)
        {
            min=AT24C02_ReadByte(0);
            sec=AT24C02_ReadByte(1);
            minisec=AT24C02_ReadByte(2);
        }

        nixie_SetBuf(1,min/10);
        nixie_SetBuf(2,min%10);
        nixie_SetBuf(3,11);
        nixie_SetBuf(4,sec/10);
        nixie_SetBuf(5,sec%10);
        nixie_SetBuf(6,11);
        nixie_SetBuf(7,minisec/10);
        nixie_SetBuf(8,minisec%10);

    }
}

void Sec_Loop()
{
    if(flag)
    {
        if(m==1)
        {
            minisec++;
            if(minisec>=100)
            {
                minisec=0;
                sec++;
            }
            if(sec>=60)
            {
                sec=0;
                min++;
                if(min>=60)
                {
                    min=0;
                }
            }

        }
        if(m==0)
        {        
            minisec--;
            if(min<0)
            {
                flag=0;
                min=0;
                sec=0;
                minisec=0;
            }
            if(minisec<0)
            {
                minisec=99;
                sec--;
            }
            if(sec<0)
            {
                sec=59;
                min--;
            }
        
        }

    }
}

void Timer0_Routine() interrupt 1
{
    static unsigned int T0Count1,T0Count2,T0Count3;
	TL0 = 0x18;				//设置定时初始值
	TH0 = 0xFC;				//设置定时初始值
    T0Count1++;
    if(T0Count1>=20)
    {
        T0Count1=0;
        Key_Loop();
    }
    T0Count2++;
    if(T0Count2>=1)
    {
        T0Count2=0;
        nixie_Loop();
    }
    T0Count3++;
    if(T0Count3>=10)
    {
        T0Count3=0;
        Sec_Loop();
    }
}
